import { ref } from "vue";
import type { FormInst, FormRules } from "naive-ui";

import { api } from "@/api";
import { useUserStore } from "@/stores/user";

export interface Register {
  username: string;
  password: string;
  repassword: string;
}

const user = useUserStore();

export function useRegister() {
  const registerRef = ref<FormInst | null>(null);

  const registerModel = ref<Register>({
    username: "",
    password: "",
    repassword: "",
  });

  async function toRegister() {
    const res = (await api.post("/register", registerModel.value)).data;
    localStorage.setItem("token", res?.data?.token);
    await user.getUserInfo();
    return res?.msg;
  }

  const registerRules: FormRules = {
    username: [
      {
        required: true,
        validator(_, value: string) {
          if (value.length < 6) {
            return new Error("用户名不能少于6位");
          }
          return true;
        },
        trigger: ["input", "blur"],
      },
    ],
    password: [
      {
        required: true,
        validator(_, value: string) {
          if (value.length < 6) {
            return new Error("密码不能少于6位");
          }
          return true;
        },
        trigger: ["input", "blur"],
      },
    ],
    repassword: [
      {
        required: true,
        validator(_, value: string) {
          if (value !== registerModel.value.password) {
            return new Error("两次输入的密码不一致");
          }
          return true;
        },
        trigger: ["input", "blur"],
      },
    ],
  };

  return {
    registerRef,
    registerModel,
    toRegister,
    registerRules,
  };
}
